/**
 * 用户管理 Mock 数据
 */

import type { User, UserCreateRequest, UserUpdateRequest, UserListParams } from '@/api/user'
import { randomDelay, generateId, generatePhone, generateEmail, generateRandomDate, formatDate } from './index'

// Mock 用户数据
const mockUsers: User[] = [
  {
    id: 'admin001',
    username: 'admin',
    realName: '系统管理员',
    role: 'ADMIN',
    phone: '13800138000',
    email: 'admin@example.com',
    avatar: '',
    status: 'ACTIVE',
    createdTime: '2024-01-01T00:00:00.000Z',
    lastLoginTime: generateRandomDate(7)
  },
  {
    id: 'school_admin001',
    username: 'school_admin01',
    realName: '张校长',
    role: 'SCHOOL_ADMIN',
    phone: generatePhone(),
    email: 'zhang@example.com',
    avatar: '',
    status: 'ACTIVE',
    createdTime: generateRandomDate(30),
    lastLoginTime: generateRandomDate(3),
    schoolId: 'school1'
  },
  {
    id: 'teacher001',
    username: 'teacher001',
    realName: '李老师',
    role: 'TEACHER',
    phone: generatePhone(),
    email: 'li@example.com',
    avatar: '',
    status: 'ACTIVE',
    createdTime: generateRandomDate(25),
    lastLoginTime: generateRandomDate(1),
    schoolId: 'school1'
  },
  {
    id: 'teacher002',
    username: 'teacher002',
    realName: '王老师',
    role: 'TEACHER',
    phone: generatePhone(),
    email: 'wang@example.com',
    avatar: '',
    status: 'ACTIVE',
    createdTime: generateRandomDate(20),
    lastLoginTime: generateRandomDate(2),
    schoolId: 'school2'
  },
  {
    id: 'parent001',
    username: 'parent001',
    realName: '张爸爸',
    role: 'PARENT',
    phone: generatePhone(),
    email: 'zhangbaba@example.com',
    avatar: '',
    status: 'ACTIVE',
    createdTime: generateRandomDate(15),
    lastLoginTime: generateRandomDate(1),
    schoolId: 'school1'
  },
  {
    id: 'parent002',
    username: 'parent002',
    realName: '李妈妈',
    role: 'PARENT',
    phone: generatePhone(),
    email: 'limama@example.com',
    avatar: '',
    status: 'INACTIVE',
    createdTime: generateRandomDate(10),
    schoolId: 'school1'
  },
  {
    id: 'parent003',
    username: 'parent003',
    realName: '王爸爸',
    role: 'PARENT',
    phone: generatePhone(),
    email: 'wangbaba@example.com',
    avatar: '',
    status: 'LOCKED',
    createdTime: generateRandomDate(5),
    lastLoginTime: generateRandomDate(10),
    schoolId: 'school2'
  },
  {
    id: 'parent004',
    username: 'parent004',
    realName: '赵妈妈',
    role: 'PARENT',
    phone: generatePhone(),
    email: 'zhaomama@example.com',
    avatar: '',
    status: 'ACTIVE',
    createdTime: generateRandomDate(8),
    lastLoginTime: generateRandomDate(4),
    schoolId: 'school3'
  },
  {
    id: 'teacher003',
    username: 'teacher003',
    realName: '赵老师',
    role: 'TEACHER',
    phone: generatePhone(),
    email: 'zhao@example.com',
    avatar: '',
    status: 'ACTIVE',
    createdTime: generateRandomDate(18),
    lastLoginTime: generateRandomDate(2),
    schoolId: 'school3'
  },
  {
    id: 'school_admin002',
    username: 'school_admin02',
    realName: '刘校长',
    role: 'SCHOOL_ADMIN',
    phone: generatePhone(),
    email: 'liu@example.com',
    avatar: '',
    status: 'ACTIVE',
    createdTime: generateRandomDate(22),
    lastLoginTime: generateRandomDate(5),
    schoolId: 'school2'
  }
]

// 生成更多测试数据
const generateMoreUsers = (count: number): User[] => {
  const users: User[] = []
  const roles: ('ADMIN' | 'SCHOOL_ADMIN' | 'TEACHER' | 'PARENT')[] = ['TEACHER', 'PARENT']
  const names = [
    '陈老师', '林老师', '黄老师', '周老师', '吴老师',
    '徐爸爸', '孙妈妈', '马爸爸', '朱妈妈', '胡爸爸',
    '何妈妈', '高爸爸', '罗妈妈', '梁爸爸', '郑妈妈'
  ]

  for (let i = 0; i < count; i++) {
    const role = roles[Math.floor(Math.random() * roles.length)]
    const name = names[i % names.length]
    const username = `${role.toLowerCase()}${String(mockUsers.length + i + 1).padStart(3, '0')}`

    users.push({
      id: generateId(role.toLowerCase()),
      username,
      realName: `${name}${i + 1}`,
      role,
      phone: generatePhone(),
      email: generateEmail(username),
      avatar: '',
      status: Math.random() > 0.2 ? 'ACTIVE' : (Math.random() > 0.5 ? 'INACTIVE' : 'LOCKED'),
      createdTime: generateRandomDate(30),
      lastLoginTime: Math.random() > 0.3 ? generateRandomDate(7) : undefined,
      schoolId: role === 'ADMIN' ? undefined : `school${Math.floor(Math.random() * 5) + 1}`
    })
  }

  return users
}

// 扩展用户数据
mockUsers.push(...generateMoreUsers(20))

/**
 * Mock 用户 API
 */
export const mockUserAPI = {
  /**
   * 获取用户列表
   */
  async getUsers(params: UserListParams = {}) {
    await randomDelay()

    const { page = 1, pageSize = 20, keyword, role, status } = params

    let filteredUsers = [...mockUsers]

    // 关键词搜索
    if (keyword) {
      const keywordLower = keyword.toLowerCase()
      filteredUsers = filteredUsers.filter(user =>
        user.username.toLowerCase().includes(keywordLower) ||
        user.realName.toLowerCase().includes(keywordLower) ||
        (user.phone && user.phone.includes(keyword)) ||
        (user.email && user.email.toLowerCase().includes(keywordLower))
      )
    }

    // 角色筛选
    if (role) {
      filteredUsers = filteredUsers.filter(user => user.role === role)
    }

    // 状态筛选
    if (status) {
      filteredUsers = filteredUsers.filter(user => user.status === status)
    }

    // 分页
    const total = filteredUsers.length
    const startIndex = (page - 1) * pageSize
    const endIndex = startIndex + pageSize
    const list = filteredUsers.slice(startIndex, endIndex)

    return {
      code: 200,
      message: '获取成功',
      data: {
        list,
        total,
        page,
        pageSize,
        hasMore: endIndex < total
      },
      timestamp: new Date().toISOString()
    }
  },

  /**
   * 根据ID获取用户
   */
  async getUserById(userId: string) {
    await randomDelay()

    const user = mockUsers.find(u => u.id === userId)

    if (!user) {
      return {
        code: 404,
        message: '用户不存在',
        data: null,
        timestamp: new Date().toISOString()
      }
    }

    return {
      code: 200,
      message: '获取成功',
      data: user,
      timestamp: new Date().toISOString()
    }
  },

  /**
   * 创建用户
   */
  async createUser(userData: UserCreateRequest) {
    await randomDelay()

    // 检查用户名是否已存在
    if (mockUsers.some(u => u.username === userData.username)) {
      return {
        code: 400,
        message: '用户名已存在',
        data: null,
        timestamp: new Date().toISOString()
      }
    }

    const newUser: User = {
      id: generateId(userData.role.toLowerCase()),
      username: userData.username,
      realName: userData.realName,
      role: userData.role,
      phone: userData.phone,
      email: userData.email,
      avatar: userData.avatar || '',
      status: 'ACTIVE',
      createdTime: new Date().toISOString(),
      schoolId: userData.schoolId
    }

    mockUsers.push(newUser)

    return {
      code: 200,
      message: '创建成功',
      data: newUser,
      timestamp: new Date().toISOString()
    }
  },

  /**
   * 更新用户
   */
  async updateUser(userId: string, userData: UserUpdateRequest) {
    await randomDelay()

    const userIndex = mockUsers.findIndex(u => u.id === userId)

    if (userIndex === -1) {
      return {
        code: 404,
        message: '用户不存在',
        data: null,
        timestamp: new Date().toISOString()
      }
    }

    // 更新用户信息
    Object.assign(mockUsers[userIndex], userData)

    return {
      code: 200,
      message: '更新成功',
      data: mockUsers[userIndex],
      timestamp: new Date().toISOString()
    }
  },

  /**
   * 删除用户
   */
  async deleteUser(userId: string) {
    await randomDelay()

    const userIndex = mockUsers.findIndex(u => u.id === userId)

    if (userIndex === -1) {
      return {
        code: 404,
        message: '用户不存在',
        data: null,
        timestamp: new Date().toISOString()
      }
    }

    // 不能删除超级管理员
    if (mockUsers[userIndex].role === 'ADMIN' && mockUsers[userIndex].username === 'admin') {
      return {
        code: 400,
        message: '不能删除超级管理员',
        data: null,
        timestamp: new Date().toISOString()
      }
    }

    mockUsers.splice(userIndex, 1)

    return {
      code: 200,
      message: '删除成功',
      data: null,
      timestamp: new Date().toISOString()
    }
  },

  /**
   * 重置用户密码
   */
  async resetUserPassword(userId: string, newPassword: string) {
    await randomDelay()

    const user = mockUsers.find(u => u.id === userId)

    if (!user) {
      return {
        code: 404,
        message: '用户不存在',
        data: null,
        timestamp: new Date().toISOString()
      }
    }

    // Mock 实现 - 实际应该更新密码
    console.log(`重置用户 ${user.username} 的密码`)

    return {
      code: 200,
      message: '密码重置成功',
      data: null,
      timestamp: new Date().toISOString()
    }
  },

  /**
   * 激活用户
   */
  async activateUser(userId: string) {
    await randomDelay()

    const userIndex = mockUsers.findIndex(u => u.id === userId)

    if (userIndex === -1) {
      return {
        code: 404,
        message: '用户不存在',
        data: null,
        timestamp: new Date().toISOString()
      }
    }

    mockUsers[userIndex].status = 'ACTIVE'

    return {
      code: 200,
      message: '激活成功',
      data: null,
      timestamp: new Date().toISOString()
    }
  },

  /**
   * 禁用用户
   */
  async deactivateUser(userId: string) {
    await randomDelay()

    const userIndex = mockUsers.findIndex(u => u.id === userId)

    if (userIndex === -1) {
      return {
        code: 404,
        message: '用户不存在',
        data: null,
        timestamp: new Date().toISOString()
      }
    }

    // 不能禁用超级管理员
    if (mockUsers[userIndex].role === 'ADMIN' && mockUsers[userIndex].username === 'admin') {
      return {
        code: 400,
        message: '不能禁用超级管理员',
        data: null,
        timestamp: new Date().toISOString()
      }
    }

    mockUsers[userIndex].status = 'INACTIVE'

    return {
      code: 200,
      message: '禁用成功',
      data: null,
      timestamp: new Date().toISOString()
    }
  },

  /**
   * 根据角色获取用户
   */
  async getUsersByRole(role: string) {
    await randomDelay()

    const users = mockUsers.filter(u => u.role === role)

    return {
      code: 200,
      message: '获取成功',
      data: users,
      timestamp: new Date().toISOString()
    }
  },

  /**
   * 根据状态获取用户
   */
  async getUsersByStatus(status: string) {
    await randomDelay()

    const users = mockUsers.filter(u => u.status === status)

    return {
      code: 200,
      message: '获取成功',
      data: users,
      timestamp: new Date().toISOString()
    }
  },

  /**
   * 批量更新用户状态
   */
  async batchUpdateUserStatus(userIds: string[], status: 'ACTIVE' | 'INACTIVE') {
    await randomDelay()

    let updatedCount = 0

    userIds.forEach(userId => {
      const userIndex = mockUsers.findIndex(u => u.id === userId)
      if (userIndex !== -1) {
        // 不能禁用超级管理员
        if (status === 'INACTIVE' &&
            mockUsers[userIndex].role === 'ADMIN' &&
            mockUsers[userIndex].username === 'admin') {
          return
        }
        mockUsers[userIndex].status = status
        updatedCount++
      }
    })

    return {
      code: 200,
      message: `成功更新 ${updatedCount} 个用户状态`,
      data: null,
      timestamp: new Date().toISOString()
    }
  },

  /**
   * 批量删除用户
   */
  async batchDeleteUsers(userIds: string[]) {
    await randomDelay()

    let deletedCount = 0

    userIds.forEach(userId => {
      const userIndex = mockUsers.findIndex(u => u.id === userId)
      if (userIndex !== -1) {
        // 不能删除超级管理员
        if (mockUsers[userIndex].role === 'ADMIN' &&
            mockUsers[userIndex].username === 'admin') {
          return
        }
        mockUsers.splice(userIndex, 1)
        deletedCount++
      }
    })

    return {
      code: 200,
      message: `成功删除 ${deletedCount} 个用户`,
      data: null,
      timestamp: new Date().toISOString()
    }
  }
}